package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *  支付宝支付，控制器
 * */
@RestController
@Slf4j
@RequestMapping(value = "/pay")
public class PayController {

    @Autowired
    private PayService payService;
    @Autowired
    private OrdersService ordersService;

    /**
     *  下单支付
     * */
    @GetMapping(value = "/confirm" , produces = {"text/html;charset=UTF-8"})
    public Object pay (Long id) throws Exception {
        //格式是text/html，这样前端页面就能直接显示支付宝返回的html片段
        //真实场景下由post方式请求，返回code、msg、data那种格式的标准结构，让前端拿到data里的
        //html片段之后自行加载
        return payService.pay(id);
    }

    /**
     *  支付成功的回调
     * */
    @PostMapping(value = "/fallback")
    public void fallback (HttpServletRequest request) {
        log.info("-----------------进入了支付回调--------------");
        Map map = request.getParameterMap();
        //获取订单号, 编辑订单状态
        String[] orderNos = (String[]) map.get("out_trade_no");
        String orderNo = orderNos[0];

        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Orders::getStatus,2);
        updateWrapper.eq(Orders::getNumber,orderNo);
        ordersService.update(updateWrapper);
        log.info("-----------------编号:"+orderNo+"的订单状态已更新--------------");
    }
}